import { NestFactory } from '@nestjs/core';
import { AppModule } from './controller/app.module';
import { BusinessException, BusinessExceptionsFilter } from './helper/exception/catch-business-exception-filter';
import { ValidationPipe } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import * as mustacheExpress from 'mustache-express';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  const viewDir = process.env.NODE_ENV === 'production' ? 'views' : 'src/views';
  app.engine('mustache', mustacheExpress());
  app.setBaseViewsDir(viewDir);
  app.setViewEngine('mustache');

  app.enableCors();
  app.useGlobalPipes(
    new ValidationPipe({
      stopAtFirstError: true,
      transform: true,
      whitelist: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
      exceptionFactory: (errors) => {
        const error = errors[0];
        const msg = Object.values(error.constraints).join('');
        return new BusinessException(msg);
      },
    }),
  );
  app.useGlobalFilters(new BusinessExceptionsFilter());
  await app.listen(3000);
}
bootstrap();
